﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Castle.DynamicProxy;
using Newtonsoft.Json;
using OOP.Proxy.DesignPattern.Attr;

namespace OOP.Proxy.DesignPattern.Proxy
{
    public class OrderServiceInterceptor : IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            MethodInfo? method = invocation.MethodInvocationTarget;
            LogAttribute? logAttr = method.GetCustomAttribute<LogAttribute>();
            bool flag = logAttr != null;
            if (flag)
            {
                string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                if ("INFO".Equals(logAttr.Type))
                {
                    Console.WriteLine($"【INFO】{time}");
                    invocation.Proceed();
                    if (logAttr.LogResult)
                    {
                        string logRes = JsonConvert.SerializeObject(invocation.ReturnValue);
                        Console.WriteLine($"【INFO】{time} \n {logRes}");
                    }
                }
                else if ("DEBUG".Equals(logAttr.Type))
                {
                    Console.WriteLine($"【DEBUG】{time}");
                    invocation.Proceed();
                    if (logAttr.LogResult)
                    {
                        string logRes = JsonConvert.SerializeObject(invocation.ReturnValue);
                        Console.WriteLine($"【DEBUG】{time} \n {logRes}");
                    }
                }
            }
            else
            {
                invocation.Proceed();
            }
        }
    }
}
